﻿/* 
function getSelectedRange() {
    return { from: editor.getCursor(true), to: editor.getCursor(false) };
}

function autoFormatSelection() {
    var range = getSelectedRange();
    editor.autoFormatRange(range.from, range.to);
}

function commentSelection(isComment) {
    var range = getSelectedRange();
    editor.commentRange(isComment, range.from, range.to);
}
*/

ko.bindingHandlers.codeEditor = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        var editorModel = ko.utils.unwrapObservable(valueAccessor()),
            allBindings = allBindingsAccessor();

        var config = {
            lineNumbers: true,
            extraKeys: { "Alt-F": "formatSelection" },
            mode: editorModel.mode,
            onChange: function () {
                editorModel.updateContentFromUiFunction()();
            }
        }

        CodeMirror.commands.formatSelection = function (cm) {
            var range = { from: cm.getCursor(true), to: cm.getCursor(false) };
            cm.autoFormatRange(range.from, range.to);
        };

        switch (editorModel.mode)
        {
            case "javascript":
                $.extend(config.extraKeys, { "Ctrl-Space": "autocomplete" });
                CodeMirror.commands.autocomplete = function (cm) {
                    CodeMirror.simpleHint(cm, CodeMirror.javascriptHint);
                }        		
                break;
            default:
                break;
        }

        editorModel.editor = new CodeMirror.fromTextArea(element, config);

        //This links the CodeEditorViewModel content to the ContentViewModel
        // which is bound to the specific content property.
        editorModel.content = allBindings.value;
        editorModel.updateContentFromUiFunction(function () {
            editorModel.content(editorModel.editor.getValue())
        });

        editorModel.editor.setValue(editorModel.content());
    }
    ,
    update: function (element, valueAccessor) {
        var editorModel = ko.utils.unwrapObservable(valueAccessor()),
            content = editorModel.content() || "";
        editorModel.editor.getValue() != content && editorModel.editor.setValue(content);
    }
};